#!/usr/bin/env ts-node

import { DatabaseInitializer } from '../database/init';
import { cacheManager } from '../database/cache';

async function testDatabase() {
  console.log('🚀 Starting database connection test...\n');
  
  try {
    // 测试数据库连接
    const healthCheck = await DatabaseInitializer.healthCheck();
    
    console.log('📊 Database Health Check Results:');
    console.log(`  PostgreSQL: ${healthCheck.postgresql ? '✅ Connected' : '❌ Failed'}`);
    console.log(`  Redis: ${healthCheck.redis ? '✅ Connected' : '❌ Failed'}`);
    console.log(`  Overall: ${healthCheck.overall ? '✅ Healthy' : '❌ Unhealthy'}\n`);
    
    if (healthCheck.overall) {
      // 测试缓存操作
      console.log('🧪 Testing cache operations...');
      
      // 测试基本缓存操作
      await cacheManager.set('test:key', { message: 'Hello, Cache!' }, 60);
      const cachedValue = await cacheManager.get('test:key');
      console.log(`  Cache set/get: ${cachedValue ? '✅ Success' : '❌ Failed'}`);
      
      // 测试缓存统计
      const stats = await cacheManager.getStats();
      console.log(`  Cache stats: ${stats.connected ? '✅ Available' : '❌ Unavailable'}`);
      console.log(`    Memory usage: ${stats.memory_usage}`);
      console.log(`    Total keys: ${stats.total_keys}`);
      
      // 清理测试数据
      await cacheManager.del('test:key');
      console.log('  Test cleanup: ✅ Complete\n');
      
      console.log('🎉 All database tests passed!');
    } else {
      console.log('❌ Database connection failed. Please check your configuration.');
      process.exit(1);
    }
    
  } catch (error) {
    console.error('💥 Database test failed:', error);
    process.exit(1);
  } finally {
    // 关闭连接
    await DatabaseInitializer.shutdown();
    console.log('🔌 Database connections closed.');
  }
}

// 运行测试
if (require.main === module) {
  testDatabase().catch(console.error);
}

export { testDatabase };